<template>
  <div class="add-team-container">
    <h2 class="page-title">新增团队信息</h2>
    <el-form ref="teamForm"  label-width="120px">
      <!-- 团队信息部分 -->
      <h3 class="section-title">团队信息</h3>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="团队编号">
            <el-input v-model="from.id" disabled placeholder="团队编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="团队名称">
            <el-input v-model="from.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="团队头像">
            <el-upload
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
            >
              <image-upload v-model="from.avatar" ></image-upload>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-form-item label="机构" prop="institutionid">
          <el-select v-model="from.institutionid" placeholder="请选择机构" style="width: 290px">
            <el-option
                v-for="dict in institutionList"
                :key="dict.id"
                :label="dict.institutionname"
                :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-col :span="8">
          <el-form-item label="团队标签">
            <el-select v-model="j" placeholder="请选择" multiple @change="handleSelectChange">
              <el-option
                  v-for="dict in tagList"
                  :key="dict.id"
                  :label="dict.tagName"
                  :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 团队成员部分 -->
      <h3 class="section-title">团队成员 ({{ teamMembers.length }})</h3>
      <div class="doctor-grid">
        <div v-for="(member, index) in teamMembers" :key="index" class="doctor-card">
          <div class="doctor-avatar">
            <img :src="member.avator"  alt=""/>
          </div>
          <div class="doctor-info">
            <div class="doctor-name">{{ member.name }}</div>
            <div class="doctor-position">{{ member.position }}</div>
            <div class="doctor-details">签约人数 {{ member.sign }}</div>
            <div v-for="tag in member.tags" :key="tag.id" class="doctor-tag">{{ tag.tagName }}</div>
          </div>
        </div>
      </div>

      <!-- 服务包部分 -->
      <h3 class="section-title">服务包 ({{ newPackageForm.length }})</h3>
      <div class="service-packages-container" style="display: flex; flex-wrap: wrap; gap: 10px;">
        <div v-for="(packageItem, index) in newPackageForm" :key="index" class="service-package-card" style="width: 300px;">
          <div style="background-color: rgba(202,205,204,0.01); border: 1px solid rgba(39,36,36,0.2);">
            <div style="width: 100%; height: 200px; border: 1px solid rgba(39, 36, 36, 0.11); border-radius: 5px; display: flex; align-items: center; padding: 10px;">
              <div style="width: 90px; height: 90px; display: flex; justify-content: center; align-items: center;">
                <img :src="packageItem.packageImage" alt="服务包图标" style="width: 90px; height: 90px;" />
              </div>
              <div style="flex: 1; padding-left: 10px;">
                <div style="font-size: 16px; font-weight: bold;">
                  <div v-if="packageItem.packageType === 1">初级包</div>
                  <div v-if="packageItem.packageType === 2">中级包</div>
                  <div v-if="packageItem.packageType === 3">高级包</div>
                  <div v-if="packageItem.packageType === 4">特定级包</div>
                </div>
                <div style="color: #666; margin-top: 5px;">服务对象：{{ packageItem.serviceTarget }}</div>
              </div>
            </div>
          </div>
        </div>
        <div style="width: 300px; height: 200px; background-color: #f5f7fa; border-radius: 10px; display: flex; flex-direction: column; justify-content: center; align-items: center; cursor: pointer; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);" @click="dialogOverflowVisible = true">
          <div style="font-size: 30px; color: #409eff; margin-bottom: 10px;">+</div>
          <div style="font-size: 16px; color: #409eff;">添加服务包</div>
        </div>
      </div>
        </el-form>
    <div class="button-group">
      <el-button type="primary" @click="saveTeam">保存</el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>

    <el-dialog
        v-model="dialogOverflowVisible"
        title="选择添加服务包"
        width="800"
        draggable
        overflow
    >
      <div style="display: flex; flex-wrap: wrap; gap: 10px; justify-content: space-around;">
        <div
            v-for="(packageItem, index) in packageList"
            :key="index"
            class="service-package-card"
            style="width: 300px; background-color: rgba(26,179,148,0.05); border: 1px solid rgba(73,71,71,0.2);"
        >
          <div style="display: flex; justify-content: space-between; align-items: center; padding: 5px;height: 30px">
            <el-checkbox v-model="packageItem.id"></el-checkbox>
          </div>
          <div style="width: 100%; height: 150px;  border-radius: 5px; display: flex; align-items: center; padding: 10px;">
            <div style="width: 90px; height: 90px; display: flex; justify-content: center; align-items: center;">
              <img :src="packageItem.packageImage" alt="服务包图标" style="width: 90px; height: 90px;"/>
            </div>
            <div style="flex: 1; padding-left: 10px;">
              <div style="font-size: 16px; font-weight: bold;">
                <div v-if="packageItem.packageType === 1">初级包</div>
                <div v-if="packageItem.packageType === 2">中级包</div>
                <div v-if="packageItem.packageType === 3">高级包</div>
                <div v-if="packageItem.packageType === 4">特定级包</div>
              </div>
              <div style="color: #666; margin-top: 5px;">
                服务对象：{{ packageItem.serviceTarget }}
              </div>
              <div style="margin-top: 5px;">
              <span v-for="service in packageItem.services" :key="service"
                  style="display: inline-block; padding: 3px 8px; border-radius: 3px; margin-right: 5px; margin-top: 5px; color: white;"
                  :style="{backgroundColor: getServiceTagColor(service)
                }">
               {{ service }}
              </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog - footer">
          <el-button @click="dialogOverflowVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">
            确认
          </el-button>
        </div>
      </template>
      </el-dialog>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElDialog, ElForm, ElInput } from 'element-plus';
import { listInstitution } from "@/api/system/institution.js";
import { listTag } from "@/api/sysmanagement/tag.js";
import { listPackage } from "@/api/package/package.js";
import useUserStore from "@/store/modules/user.js";
import {getDoctorSysUserId} from "@/api/system/doctor";
import {getDoctorTag} from "@/api/sysmanagement/tag";
import router from "@/router/index.js";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {addTeam, addTeamDoctor, addTeamLabel, addTeamPackage} from "@/api/system/team.js";

let user=useUserStore();
const dialogOverflowVisible = ref(false)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
  },
  rules: {
    name: [
      { required: true, message: "团队名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
 let from = ref({
  id: null,
  name: null,
  avatar: null,
  institutionid: null,
  score: null,
  number: null,
  share: null,
  agency: null,
  image: null,
  time: null,
  createname: null,
  state: null,
  leader: null
})
// 获取标签
let tagList = ref([]);
/** 查询健康标签列表 */
function getListtag() {
  listTag(queryParams.value).then(response => {
    tagList.value = response.rows;
    console.log('健康标签', tagList.value)
  });
}
let j = ref([])
let jkbq ={
  teamid: 0,
  ida: 0,
  idb: 0,
  idc: 0
};
const handleSelectChange = (values) => {
  if (values.length > 3) {
    // 当选中项数量超过 3 个时，移除最后一个选中项
    const lastValue = values.pop(); // 从 values 数组中移除最后一个值
    j.value = values; // 更新 v-model 绑定的 j 的值
    ElMessage.warning('最多只能选择 3 个选项');
  }
  console.log('jkbg', j.value);

};



//获取医生信息
let doctor = ref({});
// 模拟团队成员数据
const teamMembers = ref([
]);

//通过接口查询医生信息
function getDoctor() {
  //getDoctorSysUserId(user.id).then(response => {
  getDoctorSysUserId(107).then(response => {
    doctor.value = response;

    console.log('doctor-----------', doctor.value);
    // 通过医生id获取医生的标签
    let id=doctor.value.id;
    getDoctorTag(id).then(res => {
      console.log('doctortag', res);
      doctor.value.tags=res.data;
    })
    teamMembers.value.push(doctor.value);
  })
}
getDoctor();








// 返回上一页的函数
const goBack = () => {
  // 这里可以实现返回上一页的路由跳转逻辑
router.push('/ziliao/team')
};

/** 查询机构列表 */
let institutionList = ref([]);
function getList() {
  listInstitution(queryParams.value).then(response => {
    console.log('response', response);
    institutionList.value = response.rows;
  });
}
/* 获取服务包 */
const packageList = ref([]);
const chujipackage = ref([]);
const zhongjipackage = ref([]);
const gaojipackage = ref([]);
const tedingpackage = ref([]);
const daterangeAuditTime = ref([]);
const servicePackageCategories = ref([
  {
    name: '初级包',
    packages: [

      // 更多初级包数据...
    ]
  },
  {
    name: '中级包',
    packages: [

      // 更多中级包数据...
    ]
  },
  {
    name: '高级包',
    packages: [

      // 更多高级包数据...
    ]
  },
  {
    name: '特定级包',
    packages: [

      // 更多中级包数据...
    ]
  }
]);

function getPackage2() {
  for (let i = 0; i < packageList.value.length; i++) {
    if (packageList.value[i].packageType == 1) {
      chujipackage.value.push(packageList.value[i])
    } else if (packageList.value[i].packageType == 2) {
      zhongjipackage.value.push(packageList.value[i])
    } else if (packageList.value[i].packageType == 3) {
      gaojipackage.value.push(packageList.value[i])
    }
    else if (packageList.value[i].packageType == 4) {
      tedingpackage.value.push(packageList.value[i])
    }
  }
  servicePackageCategories.value = [
    { name: '初级包', packages: chujipackage.value },
    { name: '中级包', packages: zhongjipackage.value },
    { name: '高级包', packages: gaojipackage.value },
    { name: '特定级包', packages: tedingpackage.value }
  ]
  newPackageForm.value.push(chujipackage.value[0])
}

/** 查询服务包列表 */
function getListpackage() {
  queryParams.value.params = {};
  chujipackage.value = [];
  zhongjipackage.value = [];
  gaojipackage.value = [];
  tedingpackage.value = [];
  servicePackageCategories.value = []
  if (null != daterangeAuditTime && '' != daterangeAuditTime) {
    queryParams.value.params["beginAuditTime"] = daterangeAuditTime.value[0];
    queryParams.value.params["endAuditTime"] = daterangeAuditTime.value[1];
  }
  listPackage(queryParams.value).then(response => {
    packageList.value = response.rows;
    getPackage2();
    // 打印服务包详情
    console.log('服务包详情:', packageList.value);
  });
}
// 需要添加的服务包表单数据,将服务包添加到这个数组中
const newPackageForm = ref([]);
//添加的服务包的id
let packageIds = ref([]);
//添加服务包，将选择的服务包添加到newPackageForm数组中
const handleConfirm = () => {
  // 遍历选中的服务包
  packageList.value.forEach((packageItem) => {
    if (packageItem.id) {
      // 将选中的服务包添加到 newPackageForm 数组中
      const isPakageExists = newPackageForm.value.some((item) => item.id === packageItem.id);
      if (!isPakageExists) {
        newPackageForm.value.push(packageItem);
      }
    }
  });
  dialogOverflowVisible.value = false;
  console.log('newPackageForm',newPackageForm.value)
  for (let i=0; i<newPackageForm.value.length; i++){
    packageIds.value[i]=newPackageForm.value[i].packageId;
  }
  console.log('packageIds',packageIds.value)
}


onMounted(() => {
  // 页面加载时可以执行一些初始化操作
  getList();
  getListtag();
  getListpackage();
});
console.log('newPackageForm',newPackageForm.value)

//添加团队的数据
// form.value = {
//   id: null,
//   name: null,
//   avatar: null,
//   institutionid: null,
//   score: null,
//   number: null,
//   share: null,
//   agency: null,
//   image: null,
//   time: null,
//   createname: null,
//   state: null,
//   leader: null
// }
//团队的标签
//j.value
//选择的服务包id
// packageIds = ref([])
//保存实现添加团队的信息功能的函数
//添加后的团队id
let id=0;
 const saveTeam = () => {
  from.value.leader=user.id;
   for (let i = 0; i < j.value.length; i++) {
     jkbq.ida=j.value[0];
     jkbq.idb=j.value[1];
     jkbq.idc=j.value[2];
   }
   addTeam(from.value).then(response => {
     //获取添加后的团队的id
     // console.log('添加后传递的参数',response)
     //团队id
       id=response.data;
     jkbq.teamid=id;
   // id=21;
     // //将团队的标签添加到数据库中
     // console.log('添加标签')
     //  console.log('jkbq',jkbq)
     addTeamLabel(jkbq.teamid,jkbq.ida,jkbq.idb,jkbq.idc).then(response => {
       console.log('添加标签',response)
     })
     //根据团队id添加团队的服务包
     // console.log('添加服务包')
   // console.log('packageIds',packageIds.value)
     addTeamPackage(id,packageIds.value).then(response => {
       // console.log('添加服务包',response)
     })
     //根据团队id添加团队的医生的id
    //  console.log('添加医生')
    // console.log('doctor',doctor.value.id)
     addTeamDoctor(id,doctor.value.id).then(response => {
       // console.log('添加医生',response)
     })
   });



 }





























</script>

<style scoped>
.add-team-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
}

.section-title {
  margin-top: 30px;
  margin-bottom: 15px;
}

.doctor-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  width: 1000px;
}

.doctor-card {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  text-align: center;

}

.doctor-avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover; /* 图片填充方式 */
}

.doctor-tag{
  background-color: #5fd658;
  padding: 5px 10px;
  border-radius: 5px;
  margin: 5px;
  display: inline;
}
</style>